 <template>
    <div>
        <div class='home_group_info' v-if='toInfo.isGroup==1' @click.stop.prevent='viewTargetHide'>
            <div class="home_group_title">
                <span>群设置&nbsp;({{group_detail.users.length?group_detail.users.length:0}}人)</span>
                <span>
                    <img draggable="false" src="static/image/home/close.png" @click='close_group_info'>
                </span>
            </div>
            <div class="home_group_head">
                <img class="img-border" draggable="false" src="static/image/home/groupInfo.png"/>
                <div>
                    <span style="word-break:break-all;white-space: normal;" v-show="editActive">{{group_detail.name}}<span class="group_edit" @click.stop.prevent="groupEdit" v-show='editActive&&(my_position==1||my_position==2)'></span></span>
                    <span v-show='!editActive&&(my_position==1||my_position==2)'><input class="group_edit_input" type="text" v-model='editGroupName' maxlength="60"/><span @click.stop.prevent="groupEditConfirm" class="group_edit_btn">确定</span><span class="group_edit_btn m_l_15" @click.stop.prevent="editActive=!editActive">取消</span></span>
                    <span v-show="editActive" style="line-height:1.5em;word-break:break-all;white-space: normal;">{{group_detail.introduce}}</span>
                    <input v-show='!editActive&&(my_position==1||my_position==2)' class="group_edit_input" type="text" v-model='editGroupintroduce'/>
                </div>
            </div>
            <div style="display:none;"></div>
            <div class="s_g_u_w">
                <div class="s_input_w">
                    <input type="text" v-model="search_group_user" placeholder="搜索">
                    <img src="static/image/home/clear_icon.png" v-show="search_group_user.trim()!=''" @click.stop.prevent="search_group_user=''">
                </div>
                <Tooltip content="添加成员" placement="left" v-if="my_position==1||my_position==2" style="margin:0 12px;">
                    <div class="add_u_i" @click.stop.prevent='addMember'></div>
                </Tooltip>
                 <Tooltip content="删除成员" placement="left" v-if="my_position==1||my_position==2">
                    <div class="del_u_i" @click.stop.prevent='delMemberList'></div>
                </Tooltip>
            </div>
            <div @click.stop.prevent='' class="home_group_list" v-show="search_group_user.trim()==''">
                <div class="g_l_wrap">
                    <p v-if='group_detail.users.length == 0'>获取群成员失败</p>
                    <template v-for='(item,index) in group_detail.users'>
                        <div class="groupU" :key="index+'_user'"  v-if='index<viewNum' @click.stop.prevent="getMemberInfo($event,item,'1')" @contextmenu.stop.prevent="editPosition($event,item)">
                            <img class="postion_icon" v-if="item.POSITION==1||item.POSITION==2" :src="item.POSITION==1?'static/image/home/chat/owner.png':'static/image/home/chat/manage.png'" :title="item.POSITION==1?'群主':'管理员'">
                            <img :onerror="defaultImg" draggable="false" class="img-border" :class="{gray: !item.online}"
                             :src="!$isNull(item.HEAD)?(`${$store.state.headPathUrl}${item.ID}${item.HEAD}.PNG`):`static/image/home/person_${item.GENDER==2?2:1}.png`" />
                            <div class="groupU_name">{{item.NAME | setGroupUser}}</div>
                            <span v-if="(my_position=='1'||my_position=='2')&&item.ID!=myInfo.id&&item.POSITION!='1'" class="deleteGroupUsers" @click.stop.prevent="isDeleteGroupUsers(item,index)"> <img draggable="false" src="static/image/home/deleteGroupUsers.png"> </span>
                        </div>
                    </template>
                </div>
                <div v-show='group_detail.users.length >viewNum'  @click.stop.prevent="viewMore" style="width: 100%;text-align: center;color: #1e90ff;cursor: pointer;margin: .5em 0;display:inline;">
                    查看更多
                </div>
                <div style='border-bottom: 1px solid #DDDDDD;'></div>
                <span @click="shareCode" style="padding: 10px 0;font-weight: bold;cursor:pointer;">群分享</span>
                <span style="padding: 10px 0;font-weight: bold;cursor:pointer;" @click="qrcodeShow">群二维码</span>
                <div style="display:flex;justify-content:space-between;margin-top:10px;align-items:center;font-weight: 700;">
                    <span>置顶聊天</span>
                    <i-switch v-model="topChat" @on-change="updateTopChat" />
                </div>
                <div>
                    <span>消息免打扰</span>
                    <i-switch v-model="messageFree" @on-change="updateMessageFree(1)" />
                </div>
                <div @click='clear_records_cfm(1)' class="home_group_clear">
                    清空聊天记录
                </div>
                <div class="dissolution_group" v-show="my_position==1" @click.stop.prevent='group_cfm_show'>
                    解散群聊
                </div>
                <div v-show="my_position!=1" class="quit_group" @click='clear_records_cfm(2)'>退出群聊</div>
            </div>
            <div v-show="search_group_user.trim()!=''" class="g_s_wrap">
                <template v-for='(item,index) in searchList'>
                    <div class="g_s_item" :key="index+'_search'"  v-if='index<viewNum' @click.stop.prevent="getMemberInfo($event,item,'1')" @contextmenu.stop.prevent="editPosition($event,item)">
                        <img class="postion_icon" v-if="item.POSITION==1||item.POSITION==2" :src="item.POSITION==1?'static/image/home/chat/owner.png':'static/image/home/chat/manage.png'" :title="item.POSITION==1?'群主':'管理员'">
                        <img draggable="false" :class="{gray: !item.online}" :src="item.HEAD&&item.HEAD!='null'?$get_inline_head(item.HEAD):`static/image/home/person_${item.gender==2?2:1}.png`"  :onerror="defaultImg"/>
                        <div class="groupU_name">{{item.NAME | setGroupUser}}</div>
                        <span v-if="(my_position=='1'||my_position=='2')&&item.ID!=myInfo.id&&item.POSITION!='1'" class="deleteGroupUsers" @click.stop.prevent="isDeleteGroupUsers(item,index)"> <img draggable="false" src="static/image/home/deleteGroupUsers.png"> </span>
                    </div>
                </template>
            </div>
        </div>
        <div class='home_group_info' v-else @click.stop.prevent=''>
            <div class="home_group_title">
                <span>聊天设置</span>
                <span>
                    <img draggable="false" src="static/image/home/close.png" @click='close_group_info' style='width:9px;'>
                </span>
            </div>
            <div style='align-items: center;' class="home_group_head">
                <img :onerror="defaultImg" draggable="false" class="img-border"
                 :src="!$isNull(toInfo.head)?(`${$store.state.headPathUrl}${toInfo.id}${toInfo.head}.PNG`):`static/image/home/person_${toInfo.gender==2?2:1}.png`" />
                <div>
                    <span>{{toInfo.name}}</span>
                </div>
            </div>
            <div class="home_group_list" >
                <div class="ad_m_w">
                    <span>添加新成员</span>
                    <span style="color: #CCCCCC;">
                        >
                    </span>
                </div>
                <div style='display: none;'>
                </div>
                <div style='display: none;'>
                </div>
                <div style='border-bottom: 1px solid #DDDDDD;display: none;'></div>
                <div class="home_group_top">
                    <span>置顶聊天</span>
                    <i-switch v-model="topChat" @on-change="updateTopChat" />
                </div>
                <div class="home_group_disturb">
                    <span>消息免打扰</span>
                    <i-switch v-model="messageFree" @on-change="updateMessageFree(0)" />
                </div>
            </div>
            <div @click='clear_records_cfm(1)' class="home_group_empty">
                清空聊天记录
            </div>
        </div>
        <div class="edit_menu" :style='{top:editTop+"px",left:editLeft+"px"}' v-if="editPositionShow&&my_position==1">
            <ul>
                <li v-if="curMember.POSITION==3" @click.stop.prevent="editPositionFn(2)">设为管理</li>
                <li v-if="curMember.POSITION==2" @click.stop.prevent="editPositionFn(3)">撤销管理</li>
                <li v-if="curMember.POSITION!=1" @click.stop.prevent="editPositionFn(1)">转移群主</li>
                <li @click.stop.prevent="editPositionFn(4)">取消</li>
            </ul>
        </div>
        <confirm-view v-if="clear_tip" :type="confirmType" @setConfirm='clear_records' @setClose='clearClose' :content='confirmContent' title="提示"></confirm-view>
        <cancel-group v-if='cancel_group_show' @setConfirm='cancel_group' @setClose='clearClose' content='确定解散群聊吗？' title="提示"></cancel-group>
    </div>
</template>
<script>
import {delGroup,editMemberPosition,exitGroup,editGroup,delMember,setUserDnd} from '@/api/chatSettings'
import confirmView from '../confirm_view.vue'  //通用确认框
import cancelGroup from '../confirm_view.vue'
import {mapState} from 'vuex'
	export default {
		props: {
            toInfo:{
                type:Object,
                default:{
					id: '',
					name: '',
					isGroup: false
				},
            },
            group_detail:{
                type:JSON,
                default:{
					users:[]
				}
            },
            group_info:{
                type:Object,
                default:{}
            },
            group_info_show:{
                type:Boolean,
                default:false
            },
            my_position:{
                type:String,
                default:'3'
            },
            sessionList:{
                type:Array,
                default:[]
            },
            chatList:{
                type:Array,
                default:[
					[],
					[]
				]
            },
            topChat:{
                type:Boolean,
                default:false
            },
            messageFree:{
                type:Boolean,
                default:false
            },
            setaList:{
                type:Object,
                default:{}
            },
            editPositionShow:{
                type:Boolean,
                default:false
            }
        },
        components: {
            confirmView,
            cancelGroup
        },
		data() {
			return {
                confirmContent:"",
                confirmType:0,
                editGroupintroduce:'',
                search_group_user:"",
                cancel_group_show:false,
                clear_tip:false,
                defaultImg:'this.src="static/image/home/person_1.png"',
                deleteIcon:false,
                editActive:true,
                editGroupName:'',
                viewNum:50,
                searchList:[],
                editTop:0,
                editLeft:0,
                userTimeout: null,
			}
        },
        watch:{
            search_group_user(){
                if(this.search_group_user.trim()!=''){
                    this.searchMember(this.search_group_user);
                }else{
                    this.searchList=[];
                };
            },
            toInfo(){
                this.$forceUpdate();
            },
            group_info_show(){
                if(this.group_info_show==false){
                    this.clear_tip=false;
                }
            },
            // 监听在线离线的状态
            updateUserStatus() {
                for(let item of this.group_detail.users) {
                    if(item.ID == this.updateUserStatus.userId) {
                        item.status = null;
                        item.status = this.updateUserStatus.status;
                        if(item.status == 1||item.status == 3||item.status == 4||item.status == 5||item.status == 6) {
                            item.online = true;
                        }else if(item.status == 7) {
                            item.online = false;
                        };
                        this.$forceUpdate();
                        this.userTimeout = setTimeout(() => {
                            // 对群成员进行排序
                            this.$groupSort();
                            this.userTimeout && clearTimeout(this.userTimeout);
                        }, 5000);
                    }
                };
                // this.userTimeout = setTimeout(() => {
                //     // 对群成员进行排序
                //     this.$groupSort();
                //     this.userTimeout && clearTimeout(this.userTimeout);
                // }, 5000);
            },
        },
        filters: {
            setGroupUser(str) {
				return str.length > 4 ? str.slice(0, 4) + "..." : str
            }
        },
        computed: {
			 ...mapState(["myInfo","user_hot_key","personInfoList","updateUserStatus"])
        },
		methods: {
            shareCode(){
                let introduce = this.group_detail.introduce?this.group_detail.introduce:'暂无';
                this.$emit('shareCode', {introduce:introduce,isShare:true});
            },
            delMemberList(){
                this.$emit('delMemberViewActive',true);
            },
            qrcodeShow(){
                let codeInfo={
                    shareGroupId:this.toInfo.id,
                    shareGroupName:this.toInfo.name,
                    introduce:this.group_detail.introduce?this.group_detail.introduce:'暂无',
                    shareId:this.myInfo.id,
                    shareName:this.myInfo.name,
                    department:this.myInfo.department,
                    gender:this.myInfo.gender
                };
                console.log(codeInfo, '二维码携带的信息')
                this.$emit('qrcodeShow',JSON.stringify(codeInfo));
            },
            editPositionFn(index){
                if(index==1||index==2||index==3){
                    editMemberPosition({
                        userid: this.myInfo.id,
                        fuserid:this.curMember.ID,
                        groupid: this.toInfo.id,
                        position:index
                    }).then(res=>{
                        if(res.result==200){
                            this.group_detail.users.forEach((info,key) => {
                                if(info.ID==this.curMember.ID){
                                    this.$set(info,'POSITION',index);
                                }
                                if(index=='1'&&info.ID==this.myInfo.id){
                                    this.$emit('setMyposition','3');
                                    this.$set(info,'POSITION','3');
                                }
                            });
                            if(this.searchList.length>0){
                                this.searchList.forEach((info,key)=>{
                                    if(info.ID==this.curMember.ID){
                                        this.$set(info,'POSITION',index);
                                    }
                                    if(index=='1'&&info.ID==this.myInfo.id){
                                        this.$set(info,'POSITION','3');
                                    }
                                })
                            };
                            // 对群成员进行排序
                            this.$groupSort();
                            this.$Message.info("设置成功");
                        }
                    }).catch(error=>{
                        this.$Message.info("服务器不给力,稍后再试!")
                    })
                }
                this.editPositionShow=false;
            },
            editPosition(e,item){
                if(this.my_position==1||this.my_position==2){
                    if(item.ID==this.myInfo.id){
                        return
                    }
                    this.curMember=item;
                    this.editPositionShow=true;
                    this.getCurCoor(e);
                }
                console.log(item,'群成员');
            },
            //获取坐标
			getCurCoor(e) {
				let rect = e.target.getBoundingClientRect();
				let maxTop = document.body.clientHeight
				this.editTop = maxTop - rect.top - 100 > 0 ? rect.top+10 : maxTop;
				this.editLeft = rect.left-60||0;
			},
            searchMember(value){
                this.searchList=[];
                console.log(this.group_detail.users,'成员');
                for(let i=0;i<this.group_detail.users.length;i++){
                    // console.log(this.group_detail.users[i].NAME.indexOf(value),'搜索结果1')
                    if(this.group_detail.users[i].NAME.indexOf(value)!=-1){
                        // console.log(this.group_detail.users[i].NAME.indexOf(value),'搜索结果')
                        this.searchList.push(this.group_detail.users[i]);
                    }
                }
            },
            group_cfm_show(){
                this.cancel_group_show=true;
            },
            clear_records_cfm(type){
                this.confirmType=type;
                if(type==1){
                    this.confirmContent="确定清空聊天记录吗?";
                }else if(type==2){
                     this.confirmContent="确定退出群聊吗?";
                }
                this.clear_tip=true;
            },
            clearClose(){
                this.clear_tip=false;
                this.cancel_group_show=false;
            },
            viewTargetHide(){
                this.$emit('viewTargetHide');
            },
            cancel_group() {
                this.$startLoading('.loading_group');
                delGroup({
                    userid: this.myInfo.id,
					groupid: this.toInfo.id
                }).then(res=>{
                    this.$endLoading();
                    this.cancel_group_show=false;
					this.$Message.info("解除群聊 成功！")
                }).catch(error=>{
                    this.$endLoading();
                    this.$Message.info("服务器不给力,稍后再试!")
                })
                this.$emit('viewTargetHide');
			},
            deleteMember(){
				this.$emit('viewTargetHide');
				this.deleteIcon=!this.deleteIcon;
			},
            //清除聊天记录  --退出群聊
			clear_records(type) {
                if(type==1){
                    this.clearClose();
                    this.$emit('clear_records');
                }else if(type==2){
                    exitGroup({
                        userid: this.myInfo.id,
                        groupid: this.toInfo.id
                    }).then(res=>{
                        if(res.result==200){
                            this.$emit('getGroupUser');
                            this.$Message.info("您退出了该群聊");
                            this.$emit('viewTargetHide');
                            // 新增判断如果群人员少于2人，自动解散群聊

                        }else{
                            this.$Message.info(res.msg);
                        }
                        this.clearClose();
                    }).catch(error=>{
                        this.clearClose();
                        this.$Message.info("服务器不给力,稍后再试!")
                    })
                }
			},
            //免打扰设置
			updateMessageFree(type) {
                // 新增设置消息免打扰接口
                // type: 0 个人 1 群
                // option: 操作:1:增加,2:删除
                // times: 勿扰截止时间(预留)
                let option = this.messageFree ? 1 : 2;
                setUserDnd({
                    userId: this.myInfo.id,
                    objectId: this.toInfo.id,
                    type: type,
                    option: option
                }).then(res=>{
                    if(res.result === 200) {
                        this.$Message.success(res.data);
                        this.$emit('updateMessageFree',this.messageFree);
                    };
                }).catch(error=>{
                    console.log(error,'error');
                })
			},
            updateTopChat(e){
                this.$emit('updateTopChat',e);
            },
            //确认删除
            isDeleteGroupUsers(item){
                console.log('确认删除==>',item)
                this.$confirm('此操作将删除该人员, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteGroupUsers(item)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //删除群成员
			deleteGroupUsers(item,index){
				if(this.my_position=='1'||this.my_position=='2'){
                    // this.$emit('viewTargetHide','');
                    console.log(this.myInfo.id,item.ID,this.toInfo.id,'删除成员')
                    delMember({
                        userid: this.myInfo.id,
                        fuserid: item.ID,
                        groupid: this.toInfo.id,
                    }).then(res=>{
                        if(res.result==200){
                            this.group_detail.users.forEach((info,index) => {
                                if(info.ID==item.ID){
                                    this.group_detail.users.splice(index,1);
                                }
                            });
                            if(this.searchList.length>0){
                                this.searchList.forEach((info,index)=>{
                                    if(info.ID==item.ID){
                                        this.searchList.splice(index,1);
                                    }
                                })
                            }
							// this.group_detail.users.splice(index,1);
						}
						console.log(res,'删除成员');
						this.$forceUpdate();
                    }).catch(error=>{
                        this.$Message.info("服务器连接失败,稍后再试");
                    })
				}

			},
            getMemberInfo(e,temp,isGroup){
                this.$emit('getMemberInfo',e,temp,isGroup)
            },
            //群成员查看更多
			viewMore(){
				if(this.viewNum>=this.group_detail.users.length){
					return;
				}
				if(this.viewNum+100>this.group_detail.users.length){
					this.viewNum+=this.group_detail.users.length-this.viewNum+1
				}else{
					this.viewNum+=100;
				}
			},
             //关闭群信息
			close_group_info(){
                this.$emit('close_group_info');
				this.deleteIcon=false;
				this.$forceUpdate();
            },
            addMember(){
                this.$emit('addMember');
            },
            groupEdit(){
                this.editActive=!this.editActive;
				this.editGroupName=this.group_detail.name;
                if(this.group_detail.introduce){
                    this.editGroupintroduce=this.group_detail.introduce;
                }
            },
            self_update_session(type, value, id, dura,time) {
				for (let i in this.sessionList) {
					if (this.sessionList[i].id == this.toInfo.id) {
                        this.$set(this.sessionList[i],'value',value);
                        this.$set(this.sessionList[i],'duration',dura);
                        this.$set(this.sessionList[i],'type',type);
                        this.$set(this.sessionList[i],'messageId',id);
                        this.$set(this.sessionList[i],'time',time);
					}
				}
			},
            groupEditConfirm(){
				console.log('请求群id',this.toInfo.id)
                let initid = this.$func.uuid();
                if(this.editGroupName.length>15){
                    this.$Message.success('群名称超过最大长度(15位)',3);
                    return;
                }
                let obj = {
                    userid: this.myInfo.id,
					name: this.editGroupName.trim()==''?'群聊':this.editGroupName,
					id:this.toInfo.id,
					key:initid,
					introduce:this.editGroupintroduce
                }
                editGroup(obj).then(res=>{
                    console.log(res,'群名称修改');
					if (res.result == 200) {
                        this.group_detail.introduce = this.editGroupintroduce;
						this.group_info.name=this.editGroupName;
						this.toInfo.name=this.editGroupName.trim()==''?'群聊':this.editGroupName;
						this.group_info.name=this.editGroupName.trim()==''?'群聊':this.editGroupName;
						this.editActive=true;
                        this.$Message.success('修改成功');
                        // 新增获取群列表刷新this.groupList缓存
						this.$emit('getGroupList');
					} else {
						this.$Message.success('修改失败');
					}
                }).catch(error=>{
                    this.$Message.success('服务器出错,稍后再试22');
                })
            }
		}
	}
</script>
